#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# TwiTalker - The Twitter Gtalk BOT
# Copyright 2009-2010 Kavin Gray
# See LICENSE for details.
#
#
from django.utils import simplejson
from google.appengine.ext import db
from db_model import TwiDbA, TwiDbB, TwiDbC, TwiDbD, TwiDbE, TwiDbF, TwiDbG, TwiDbH, TwiDbI, TwiDbJ, TwiCount,TwiError

DATABASE={1:"TwiDbA",2:"TwiDbB",3:"TwiDbC",4:"TwiDbD",5:"TwiDbE",6:"TwiDbF",7:"TwiDbG",8:"TwiDbH",9:"TwiDbI",10:"TwiDbJ"}
TWIFS={1:TwiDbA,2:TwiDbB,3:TwiDbC,4:TwiDbD,5:TwiDbE,6:TwiDbF,7:TwiDbG,8:TwiDbH,9:TwiDbI,10:TwiDbJ}

class DBService():

    def __init__(self ,add='' ):
        
        self._add=add                   # the msg sender's gtalk address
        self._results = None            # query result



    def getQuery(self):
        '''
        Return the query result
        '''
        return self._results


    def setQuery(self,db_name):
        '''
        Query the Datastore
        '''
        inquiry='SELECT * FROM '+db_name
        self._results = db.GqlQuery(inquiry)        
        
        
    def isUser(self):
        '''
        Check if the msg sender have bind to the accout
        Yes => Return Ture
        No => Return False
        '''
        cursor=1
        while(cursor<=10):
            
            command="SELECT * FROM "+DATABASE[cursor]+" WHERE email = '"+self._add+"'"
            q = db.GqlQuery(command)
            num = q.count()
            
            if(num<>0):
                if(num==1):
                    self._results=q
                    return True
                else:
                    # delete and update counter..normally this case should not occur..
                    db.delete(q)
                    twiNum=db.GqlQuery("SELECT * FROM TwiCount")
                    for en in twiNum:
                        en.count=en.count-num
                        db.put(en)
                        return False
                    
            cursor=cursor+1
            
        if(cursor==11):
            return False


    def setRuntime(self,enty,rtime):
        enty.runtime=rtime
        db.put(enty)


    def setMsgid(self,enty,msgid):
        enty.msgid=msgid
        db.put(enty)


    def setDMid(self,enty,dmid):
        enty.dmid=dmid
        db.put(enty)


    def setName(self,enty,name):
        
        enty.name=name
        db.put(enty)        


    def setMode(self,enty,mode,live_list=''):
        
        if(mode=='on'):
            enty.msgid=0
            enty.mode='on'
        elif(mode=='self'):
            enty.mode='self'
        elif(mode=='live'):
            if(live_list<>''):
                enty.list=live_list
            enty.msgid=0
            enty.mode='live'
        elif(mode=='off'):
            enty.mode='off'
        elif(mode=='idon'):
            enty.rt=True
        elif(mode=='idoff'):
            enty.rt=False
            
        db.put(enty)


    def setTime(self,enty,settime):
        '''
        set the refresh rate
        '''
        enty.settime=settime
        enty.runtime=1
        db.put(enty)


    def setMListcursor(self,enty,previous_cursor,next_cursor):
        enty.mlistcursor[0]=previous_cursor
        enty.mlistcursor[1]=next_cursor
        db.put(enty)


    def setListcursor(self,enty,previous_cursor,next_cursor):
        enty.listcursor[0]=previous_cursor
        enty.listcursor[1]=next_cursor
        db.put(enty)         


    def setListedcursor(self,enty,previous_cursor,next_cursor):
        enty.listedcursor[0]=previous_cursor
        enty.listedcursor[1]=next_cursor
        db.put(enty)
        

    def createCounter(self):
        counter=TwiCount()
        counter.count=1
        db.put(counter)


    def setCounter(self,counter,num):
        counter.count=num
        db.put(counter)


    def getCounter(self):
        q = db.GqlQuery("SELECT * FROM TwiCount")
        return q[0].count
        
               

    def createUser(self,cursor,tww,actoken,actokense):
        
        newEntity=TWIFS[cursor]()
        newEntity.name=tww.getName().lower()
        newEntity.email=self._add.lower()
        newEntity.actoken=actoken
        newEntity.actokense=actokense
        newEntity.msgid=0
        try:
            statecode=tww.getDMessage(1)
            if(statecode==200):
                contents = simplejson.loads(tww.getContent())
                if(contents<>[]):
                    newEntity.dmid=contents[0]['id']
        except:
            pass
        db.put(newEntity)



    def delUser(self,enty):
        enty.delete()



    def defaultUser(self,enty,tww,actoken,actokense):
        enty.actoken=actoken
        enty.actokense=actokense
        enty.name=tww.getName()
        enty.msgid=0
        enty.listcursor=['-1','-1']
        enty.listedcursor=['-1','-1']
        enty.mlistcursor=['-1','-1']
        try:
            statecode=tww.getDMessage(1)
            if(statecode==200):
                contents = simplejson.loads(tww.getContent())
                if(contents<>[]):
                    enty.dmid=contents[0]['id']
        except:
            pass
        db.put(enty)
        